package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WeMediaConstants;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmCheckDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.util.WmMediaThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/2/1 11:05
 * @Version 1.0
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService{

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;
    @Autowired
    private WmNewsTaskService taskService;


    @Override
    public ResponseResult pageList(WmNewsPageReqDto dto) {
        //参数校验
        dto.checkParam();
        //分页对象构造
        IPage page = new Page(dto.getPage(),dto.getSize());
        //构造查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态筛选
        wrapper.eq(dto.getStatus() != null,WmNews::getStatus,dto.getStatus());
        //开始结束时间
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            wrapper.between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //频道
        wrapper.eq(dto.getChannelId() != null,WmNews::getChannelId,dto.getChannelId());
        //关键字
        wrapper.like(!StringUtils.isEmpty(dto.getKeyword()), WmNews::getTitle,dto.getKeyword());
        //用户
        wrapper.eq(WmNews::getUserId, WmMediaThreadLocalUtil.getUser().getId());

        wrapper.orderByDesc(WmNews::getCreatedTime);
        //查询结果
        page(page,wrapper);
        //封装结果
        ResponseResult result = new PageResponseResult(dto.getPage(),(int)page.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public ResponseResult submit(WmNewsDto newsDto) {
        //参数校验
        if(StringUtils.isEmpty(newsDto.getTitle()) || StringUtils.isEmpty(newsDto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //文章保存（含修改）
        WmNews wmNews = saveOrUpdateNews(newsDto);
        //判断是否为草稿
        if(newsDto.getStatus() == WmNews.Status.NORMAL.getCode()){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //关联正文中图片和素材的关系
        //获取正文中所有的图片
        List<String> images = getAllImages(newsDto.getContent());
        saveRelations(images,wmNews.getId(),WeMediaConstants.REFERENCE_CONTENT);

        //关联封面图片和素材的关系
        saveRelationForCover(images,wmNews,newsDto);

        if(newsDto.getPublishTime() != null){
            taskService.addTask(wmNews);
        }else {
            //内容安全检测
            autoScanService.autoScan(wmNews);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 处理封面图片和素材关系
     * @param contentImages
     * @param wmNews
     */
    private void saveRelationForCover(List<String> contentImages, WmNews wmNews,WmNewsDto newDto) {
        List<String> images = newDto.getImages();
        //如果封面类型是自动
        if(newDto.getType() == WeMediaConstants.TYPE_AUTO){
            int size = contentImages.size();
            if(size >= 3){
                wmNews.setType(WeMediaConstants.TYPE_MANY_PIC);
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }else if(size >=1 && size < 3){
                wmNews.setType(WeMediaConstants.TYPE_SIGNAL_PIC);
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            }else{
                wmNews.setType(WeMediaConstants.TYPE_NO_PIC);
            }
            if(!CollectionUtils.isEmpty(images)) {
                wmNews.setImages(StringUtils.collectionToCommaDelimitedString(images));
            }
            updateById(wmNews);
        }
        if(!CollectionUtils.isEmpty(images)){
            saveRelations(images, wmNews.getId(),WeMediaConstants.REFERENCE_COVER);
        }
    }

    /**
     * 保存正文图片和素材的关系
     *
     * @param images
     * @param newsId
     */
    private void saveRelations(List<String> images, Integer newsId,short type) {
        if(CollectionUtils.isEmpty(images)){
            return;
        }
        //查询所有素材ID
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(WmMaterial::getUrl,images);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);

        List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

        wmNewsMaterialMapper.saveAll(materialIds,newsId,type);
    }

    /**
     *
     * 获取正文中所有的图片
     * @param content
     * @return
     */
    private List<String> getAllImages(String content) {
        List<String> images = new ArrayList<>();
        List<Map> imageList = JSON.parseArray(content,Map.class);
        for(Map map : imageList){
            String type = map.get("type").toString();
            String value = map.get("value").toString();
            if("image".equals(type)){
                images.add(value);
            }
        }
        return images;
    }


    /**
     * 保存或者修改文章
     * 修改文章的时候需要先删除素材关联关系
     *
     * @param newsDto
     */
    private WmNews saveOrUpdateNews(WmNewsDto newsDto) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(newsDto,wmNews);
        //图片处理
        if(!CollectionUtils.isEmpty(newsDto.getImages())){
            String imageStr = StringUtils.collectionToCommaDelimitedString(newsDto.getImages());
            wmNews.setImages(imageStr);
        }

        if(newsDto.getType() == WeMediaConstants.TYPE_AUTO){
            wmNews.setType(null);
        }

        wmNews.setUserId(WmMediaThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        if(newsDto.getId() == null){
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,newsDto.getId()));
            //删除关联关系
            updateById(wmNews);
        }
        return wmNews;
    }

    @Override
    public ResponseResult wmCheckPageList(NewsAuthDto newsAuthDto) {
        //分页对象构造
        IPage<WmNews> page = new Page(newsAuthDto.getPage(), newsAuthDto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态
        wrapper.eq(newsAuthDto.getStatus()!=null,WmNews::getStatus,newsAuthDto.getStatus());
        //标题查询
        wrapper.like(newsAuthDto.getTitle()!=null,WmNews::getTitle,newsAuthDto.getTitle());
        //排序规则
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //查询结果
        page(page, wrapper);
        //封装结果
        PageResponseResult result = new PageResponseResult(newsAuthDto.getPage(), newsAuthDto.getSize(), (int) page.getTotal());

        List<WmNews> records = page.getRecords();
        List<WmCheckDto> wmCheckDtos = new ArrayList<>();
        for (WmNews record : records) {
            WmUser wmUser = wmUserMapper.selectNameById(record.getUserId());
            String name = "未知";
            if (wmUser!=null){
                name = wmUser.getName();
            }
            WmCheckDto wmCheckDto = new WmCheckDto();
            BeanUtils.copyProperties(record,wmCheckDto);
            wmCheckDto.setAuthorName(name);
            wmCheckDtos.add(wmCheckDto);
        }

        result.setData(wmCheckDtos);

        return result;
    }

    @Override
    public ResponseResult detail(Integer id) {
        WmNews wmNews = getById(id);
        //属性拷贝

        WmCheckDto wmCheckDto = new WmCheckDto();
        BeanUtils.copyProperties(wmNews,wmCheckDto);
        //作者详情塞入
        WmUser wmUser = wmUserMapper.selectNameById(wmNews.getUserId());
        String authName = "神秘者";
        if (wmUser != null){
            authName = wmUser.getName();
        }
        wmCheckDto.setAuthorName(authName);

        return ResponseResult.okResult(wmCheckDto);
    }

    @Override
    public ResponseResult checkFail(NewsAuthDto newsAuthDto) {
        WmNews wmNews = wmNewsMapper.selectById(newsAuthDto.getId());
        wmNews.setStatus((short) 2);
        wmNews.setReason(newsAuthDto.getMsg());
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmChannelMapper channelMapper;
    @Autowired
    private WmUserMapper userMapper;

    @Override
    public ResponseResult checkPass(NewsAuthDto newsAuthDto) {
        //创建app端的文章信息，并更新自媒体文章的状态
        WmNews wmNews = wmNewsMapper.selectById(newsAuthDto.getId());
        wmNews.setStatus((short) 4);
        //保存到app端
        saveToApp(wmNews);
        //更新数据库
        wmNewsMapper.updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //保存到app端
    private ResponseResult saveToApp(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);

        dto.setLayout(wmNews.getType());
        dto.setAuthorId(wmNews.getUserId());

        //渠道处理
        WmChannel channel = channelMapper.selectById(wmNews.getChannelId());
        dto.setChannelName(channel == null ? null : channel.getName());

        //用户昵称
        WmUser user = userMapper.selectById(wmNews.getUserId());
        dto.setAuthorName(user.getNickname());

        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        return articleClient.saveArticle(dto);
    }
}